﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebNext.Domain.Interfaces;
using NHibernate;
using WebNext.Domain.Entities;
using WebNext.DataAccess.Infrastructure;

namespace WebNext.DataAccess.Repositories
{
	public abstract class EntitiesRepository<T> : IEntitesRepository<T> where T : Entity
	{
		protected NHibernateContext databaseContext;

		public EntitiesRepository(IDatabaseContext databaseContext)
		{
			this.databaseContext = databaseContext as NHibernateContext;
		}

		public virtual void Save(T entity)
		{
			this.databaseContext.Session.SaveOrUpdate(entity);
		}

		public virtual void Delete(T entity)
		{
			this.databaseContext.Session.Delete(entity);
		}

		public virtual T GetById(int id)
		{
			return this.databaseContext.Session.QueryOver<T>().Where(t => t.Id == id).SingleOrDefault();
		}

		public virtual IEnumerable<T> GetAll()
		{
			return this.databaseContext.Session.QueryOver<T>().List();
		}

		public virtual IEnumerable<T> GetAll(int pageNumber, int pageSize)
		{
			return this.databaseContext.Session.QueryOver<T>().Skip(pageNumber * pageSize).Take(pageSize).List();
		}

		public virtual int GetCount()
		{
			return this.databaseContext.Session.QueryOver<T>().RowCount();
		}

		public void Rollback()
		{
			this.databaseContext.Rollback();
		}
	}
}
